package com.ly.hotel.view.setting;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.view.common.PullDownMenu;
import com.ly.hotel.view.common.PullDownMenu.SelectListner;

public class SystemUpdateDeviceInfo extends Dialog {

	public static final int UPDATE_GROUP_DATA = 1;
	public static final int UPDATE_DEV_DATA = 2;
	public static final int SHOW_LOG = 3;
	public static final int UDP_REV_DATA =  15;
	public PullDownMenu groupName;
	public EditText deviceName;
	private List<String> group_data_list;
	private List<String> device_data_list;
	private Button okBtn;
	private Button exitBtn;
	private Context context;
	private TextView info;
	private HashMap<String, String> mydevMacMap = new HashMap<String, String>();
	private ThisHandler handlerMsg = new ThisHandler(this);
	private String selectGroupId = "";
	private String selectGroupName = "";
	
    private MulticastSocket ms;
    private static String MulticastHost="238.9.9.1";
    private static int PORT = 8304;
    InetAddress receiveAddress;
    String result = "";
    
	public SystemUpdateDeviceInfo(Context context) {
		super(context);
		this.context = context;
	}

	public SystemUpdateDeviceInfo(Context context, int theme) {
		super(context, theme);
		this.context = context;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.setting_update_device_info);
		initView();
		getGroup();
		deviceName.setText(MyApplication.getDeviceInfo().getName());
		deviceName.setFocusable(false);
		InputMethodManager inputManager = (InputMethodManager) deviceName  
                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(deviceName.getWindowToken(),0);
	}

	@Override
	protected void onStart() {
		super.onStart();
		initUdpRev();
	}
	
	private void initView() {
		
		groupName = (PullDownMenu) findViewById(R.id.groupName);
		deviceName = (EditText) findViewById(R.id.deviceName);
		deviceName.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//设置可获得焦点  
				Log.i("setting", "deviceName onClick");
				deviceName.setEnabled(true);
				deviceName.setFocusable(true);  
				deviceName.setFocusableInTouchMode(true);  
				deviceName.setCursorVisible(true);
	            //请求获得焦点  
				deviceName.requestFocus();  
	            //调用系统输入法  
	            InputMethodManager inputManager = (InputMethodManager) deviceName  
	                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);  
	            inputManager.showSoftInput(deviceName, 0);
			}
		});
		deviceName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				// TODO Auto-generated method stub
				if(arg1){
					if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
						deviceName.setFocusable(false);
						InputMethodManager inputManager = (InputMethodManager) deviceName  
				                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
						inputManager.hideSoftInputFromWindow(deviceName.getWindowToken(),0);
					}
				}
			}
		});

		deviceName.setOnEditorActionListener(new EditText.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				Log.i("setting", arg1+"");
				if (arg1 == EditorInfo.IME_ACTION_DONE) {  
					deviceName.setFocusable(false);
					InputMethodManager inputManager = (InputMethodManager) deviceName  
			                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					inputManager.hideSoftInputFromWindow(deviceName.getWindowToken(),0);
					return true;
				}
				return false;
			}  
	          
	    }); 
/*		deviceName.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				if(arg2.getKeyCode() == KeyEvent.KEYCODE_DEL){
					if(deviceName.getText().toString().length() >= 1){
						deviceName.setText(deviceName.getText().toString().substring(0, deviceName.getText().toString().length()-1));
					}
				}
				
				return false;
			}
		});*/
		
		okBtn = (Button) findViewById(R.id.okBtn);
		info = (TextView) findViewById(R.id.testInfoTxt);
		okBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				info.append("新的座位号(" + groupName.getText().split(",")[1]);
				info.append("-" + deviceName.getText() + ")\r\n");
				Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show();
				updateDeviceInfo();
				udpSendInfo();
			}
		});
		
		exitBtn = (Button) findViewById(R.id.exitBtn);
		exitBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dismiss();
			}
		});
	}
	
	private void getGroup(){
		//数据
		group_data_list = new ArrayList<String>();
//		group_data_list.add("休息厅");
//        group_data_list.add("VIP包房");
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				List<String> groups = null;
//				info.append("获取设备类别\r\n");
				
				try {
					groups = SPAService.getAllGroup();
					
					if (groups != null) {
						group_data_list.addAll(groups);
						handlerMsg.sendEmptyMessage(UPDATE_GROUP_DATA);
					}else{
						
					}
				} catch (HttpRequestFailException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		
		groupName.setOnSelectListner(new SelectListner() {
			
			@Override
			public void onWorkListner(final String name) {
				// TODO Auto-generated method stub
				selectGroupId = name.split(",")[0];
				selectGroupName = name.split(",")[1];
			}
		});
	}

	private void updateDeviceInfo(){
		new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							ModelBean mb;
							Message msg = new Message();
							Bundle bundle = new Bundle();
							mb = SPAService.getUpdateDeviceInfo(selectGroupId, deviceName.getText().toString());
							
							msg.what = SHOW_LOG;
							bundle.putString("log", mb.getMsg());
							msg.setData(bundle);
							handlerMsg.sendMessage(msg);
							
						} catch (HttpRequestFailException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
	}

	private void initUdpRev(){
		new Thread(){
	        public void run() {

	            try {
	                ms = new MulticastSocket(PORT);
	                receiveAddress=InetAddress.getByName(MulticastHost);
	                ms.joinGroup(receiveAddress);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }

	            byte data[] = new byte[512];
	            DatagramPacket dp = new DatagramPacket(data, 512);

	            while (true) {
	                try {
	                    ms.receive(dp);
	                    result = new String(data, 0, dp.getLength());
	                    Message msg = new Message();
	                    msg.what = UDP_REV_DATA;
	                    handlerMsg.sendMessage(msg);
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	            }

	        };
	    }.start();
	}
	public String insertString(String srcStr, String descStr, int off)
    {
        StringBuilder sb = new StringBuilder();
        
        sb.append(descStr.substring(0, off));
        sb.append(srcStr);
        sb.append(descStr.substring(off));
        
        return sb.toString();
    }
	
	public Integer getfirstNumIndex(String str){
		Integer i = -1;
		for(int j = 0;i<str.length();j++){
			if(Character.isDigit(str.charAt(j))){
				i=j;
				break;
			}
		}
		return i;
	}
	
	private void udpSendInfo(){
		new Thread(){
	        public void run() {
        	
        		try {
        			//实现把位置号自动+1，并广播到所以的机器,只支持座位号有一个数字(且第一个出现的数字)的情况
        			String tmp = deviceName.getText().toString();
					String strNum = "";
					int numIndex = getfirstNumIndex(tmp);//第一次出现数字的索引
					if(numIndex == -1){
						info.append("座位号不包含数字，不能为你自动增加...\n\r");
						return;
					}
					
					Log.i("setting", "第一个数字出现的位置:" + numIndex);
					strNum += tmp.charAt(numIndex);
					tmp = tmp.substring(0, numIndex) + tmp.substring(numIndex+1);//取出来了，删掉
					Log.i("setting", "tmp:" + tmp + ",strNum:" + strNum);
					while(true){
						
						if(Character.isDigit(tmp.charAt(numIndex))){
							//如果是数字，就拼接上去
							strNum += tmp.charAt(numIndex);
							tmp = tmp.substring(0, numIndex) + tmp.substring(numIndex+1);//取出来了，删掉
							Log.i("setting", "tmp:" + tmp + ",strNum:" + strNum);
							if(numIndex >= tmp.length()){
								break;
							}
						} else {
							break;
						}
					}
					
					Integer num = Integer.parseInt(strNum);
					String out = insertString(num+1+"",tmp,numIndex);
					Log.i("setting", "num:" + num + "out:" + out); 
					//发出去
					sendData("deviceName:" + groupName.getText().split(",")[0] + "," + out);
				} catch (SocketException | UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

	        };
	    }.start();
	}
	
    public void sendData(String msg) throws SocketException,  UnknownHostException{  
        DatagramSocket ds = new DatagramSocket();// 创建用来发送数据报包的套接字  
//        String str = "hello";  
        DatagramPacket dp = new DatagramPacket(msg.getBytes(),  
        		msg.getBytes().length,  
                InetAddress.getByName("172.16.255.255"), 8304);  
        // 构造数据报包，用来将长度为 length 的包发送到指定主机上的指定端口号  
        try {  
            ds.send(dp);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        ds.close();  
          
    }  
    
	private static class ThisHandler extends Handler {
		private WeakReference<SystemUpdateDeviceInfo> wrActivity;

		public ThisHandler(SystemUpdateDeviceInfo activity) {
			wrActivity = new WeakReference<SystemUpdateDeviceInfo>(activity);
		}
   
		@Override
		public void handleMessage(Message message) {
			SystemUpdateDeviceInfo act = wrActivity.get(); 
			
			if (act != null) {
				switch (message.what) {
				case UPDATE_GROUP_DATA:
					act.groupName.setData("分组", act.group_data_list, false);
					break;
				case UPDATE_DEV_DATA:
					
					break;
				
				case SHOW_LOG:
					act.info.append(message.getData().getString("log") + "\r\n");
					break;
					
				case UDP_REV_DATA:
	               Log.i("setting", "result-->" + act.result);
	               if(act.result.startsWith("deviceName:")){
	            	   act.deviceName.setText(act.result.replace("deviceName:", "").split(",")[1]);
	            	   for(String s:act.group_data_list){
	            		   if(s.startsWith(act.result.replace("deviceName:", "").split(",")[0] + ",")){
	            			   act.groupName.setText(s);
	            			   act.selectGroupId = s.split(",")[0];
	            			   act.selectGroupName = s.split(",")[1];
	            		   }
	            	   }
	            	  
	               }
	               break;
				}
			}
		}
	}
	
}
